#include<cstdlib>
#include<string>
#include<fstream>
#include<cmath>

#include<formic/lattice_ed/lattice_ed.h>
#include<formic/exception.h>

int main(int argc, char ** argv) {

  if (argc != 3)
    throw formic::Exception("Wrong number of arguments.  Correct usage:  lattice_ed_test3 input_file output_file");

  const int exit_code = formic::led::main(argc, argv);
  if (exit_code != EXIT_SUCCESS)
    throw formic::Exception("bad exit code of %i from formic::led::main") % exit_code;

  // open output file and check that the energy is correct
  std::ifstream ifs("output.txt");
  std::string line;
  double energy = 0.0;
  while ( !ifs.eof() && ifs.good() ) {
    std::getline(ifs, line);
    if ( line.find("iter      smallest eigenvalue       largest eigenvalue     lanczos elapsed time") != std::string::npos ) {
      std::string word;
      double x;
      while (ifs >> word && word != "lanczos")
        ifs >> energy >> x >> x;
      if ( !ifs || ifs.eof() )
        throw formic::Exception("output file ended prematurely when searching for energy");
    }
  }
  ifs.close();
  const double correct_energy = -6.281867066;
  if ( std::abs(correct_energy - energy) > 1.0e-7 )
    throw formic::Exception("Incorrect energy of %.8f.  Correct energy is %.8f.") % energy % correct_energy;

  return EXIT_SUCCESS;

}
